/**
 * Created by Administrator on 2017/9/26.
 */

$(document).ready(function () {


    var moreTpl = $('#shop-more-template').html();
    var moreCmp = Handlebars.compile(moreTpl);
    var range = 200, //距下边界长度/单位px
        maxnum = 0, //设置课程总数
        num = 0, //当前数量
        totalheight = 0,
        flag=0,
        start=1,
        length=10,
        searchName='';

    getMoreData();


    //监听滚动高度，加载数据
    $(window).on('scroll',function () {
        var srollPos = $(window).scrollTop(); //滚动条距顶部距离(页面超出窗口的高度)
        //console.log("滚动条到顶部的垂直高度: " + $(document).scrollTop());
        //console.log("页面的文档高度 ："+$(document).height());
        //console.log('浏览器的高度：'+$(window).height());
        totalheight = parseFloat($(window).height()) + parseFloat(srollPos);

        if (num>maxnum){
            return;
        }
        if (($(document).height()-range)<=totalheight&&num<=maxnum){
            //这里不能使用模板填充，应该是append()....
            getMoreData();
        }
    });

    function getMoreData() {
        if (flag){
            return ;
        }
        flag = 1;
        $('.no-info').hide();
        $('.loading').show();
        $.ajax({
            url:C.interface.homeShopMore,
            type:'post',
            dataType:'json',
            data:{
                start:start,
                length:length,
                lng:C.jingdu,
                lat:C.weidu,
                cityId:C.cityCode
            },
            success:function (response) {
                if (response.errorCode == '200'){
                    $('.loading').hide();
                    start++;
                    var data = response.data;
                    maxnum = data['count'];

                    if (maxnum == 0){
                        $('.no-info').show();
                    }
                    if (data.stores.length > 0){
                        $('#shop-box').append(moreCmp(data));
                        lazyImg();
                    }else {
                        $('.no-info').show();
                        num = maxnum +1;
                    }

                    flag = 0;

                }else if (response.errorCode == '0'){
                    alert('登录过期请重新登录');
                    againLogin();
                }else {
                    alert(response.errorMsg);
                }
            }
        });
    }


});